#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2010 Ken Lauer / sirkne at gmail dot com
#
# This software is provided 'as-is', without any express or implied
# warranty.  In no event will the authors be held liable for any damages
# arising from the use of this software.
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely, subject to the following restrictions:
# 1. The origin of this software must not be misrepresented; you must not
# claim that you wrote the original software. If you use this software
# in a product, an acknowledgment in the product documentation would be
# appreciated but is not required.
# 2. Altered source versions must be plainly marked as such, and must not be
# misrepresented as being the original software.
# 3. This notice may not be removed or altered from any source distribution.

try:
    from Box2D.examples.pgu import gui
except:
    raise ImportError('Unable to load PGU')

import os


class RobotSimulatorGUI(gui.Table):
    """
    Deals with the initialization and changing the settings based on the GUI
    controls. Callbacks are not used, but the checkboxes and sliders are polled
    by the main loop.
    """
    form = None

    def __init__(self, font, **params):
        # The framework GUI is just basically a HTML-like table
        # There are 2 columns right-aligned on the screen
        gui.Table.__init__(self, **params)
        self.form = gui.Form()

        self.font = font

        self.fg = fg = (255, 255, 255)
        self.bg = bg = (0, 0, 0)

        head = gui.Table()
        for row in [[u'随机地图', u'保存'], [u'载入...', u'测试']]:
            head.tr()
            for text in row:
                btn = gui.Button(gui.Label(text, color = bg, font = font), name = text, width = 110, height = 30)
                head.td(btn)
                head.td(gui.Spacer(5, 5))
        self.tr()
        self.td(head)

        self.split_name(u'可替换拼装块：')
        self.split_line()

        body = self.init_maps()
        self.tr()
        self.td(body)

        self.split_line()

        self.split_name(u'任务区：')
        self.split_line()

        self.split_line()

        # Add each of the checkboxes.
        for text, variable in []:
            self.tr()
            if variable == None:
                # Checkboxes that have no variable (i.e., None) are just labels.
                self.td(gui.Label(text, color=fg), align=1, colspan=2)
            else:
                # Add the label and then the switch/checkbox
                self.td(gui.Label(text, color=fg), align=1)
                self.td(gui.Switch(value=getattr(settings, variable),name=variable))


    def init_maps(self):
        grp = gui.Group(name = 'maps', value = 'm')
        body = gui.Table()

        maps = []
        for _dir, _paths, _files in os.walk('../maps'):
            for _file in _files:
                file_path = os.path.join(_dir, _file)
                maps.append(file_path)

        maps.sort()
        body.tr()
        for idx, _file in enumerate(maps):
            img = gui.Image(_file, width = 50, height = 50)
            tool = gui.Tool(grp, img, _file, width = 50, height = 50)
            body.td(tool)
            if idx % 4 != 3:
                body.td(gui.Spacer(2, 2))
            else:
                body.tr()
        return body


    def split_name(self, text: str):
        self.tr()
        self.td(gui.Spacer(5, 10))
        self.tr()
        self.td(gui.Label(text, color = self.fg, font = self.font), align = -1)


    def split_line(self):
        self.tr()
        self.td(gui.Spacer(10, 5))
        self.tr()
        self.td(gui.Color(value = self.fg, width = 260, height = 2))
        self.tr()
        self.td(gui.Spacer(10, 5))


    def updateGUI(self, settings):
        """
        Change all of the GUI elements based on the current settings
        """
        return
        for text, variable in checkboxes:
            if not variable: continue
            if hasattr(settings, variable):
                self.form[variable].value = getattr(settings, variable)

        # Now do the sliders
        for slider in sliders:
            name=slider['name']
            self.form[name].value=getattr(settings, name)

    def updateSettings(self, settings):
        """
        Change all of the settings based on the current state of the GUI.
        """
        return
        for text, variable in checkboxes:
            if variable:
                setattr(settings, variable, self.form[variable].value)

        # Now do the sliders
        for slider in sliders:
            name=slider['name']
            setattr(settings, name, int(self.form[name].value))

        # If we're in single-step mode, update the GUI to reflect that.
        if settings.singleStep:
            settings.pause=True
            self.form['pause'].value = True
            self.form['singleStep'].value = False
